// 返回成功
let resSuccess = (res, obj) => {
	return res.json({
		code: 0,
		data: obj,
		msg: 'success'
	})
}
// 返回错误
let resErr = (res, err) => {
	return res.json({
		code: 500,
		data: null,
		msg: err.name
	})
}
const obj = {
	// 新增
	add: async (model, body, res) => {
		delete body.id
		await model.create(body)
		res.json({
			code: 0,
			data: null,
			msg: 'success'
		})
	},
	// 查询分页
	page: async (model, body, res, arr) => {
		let currentPage = parseInt(body.currentPage) // 页码
		let pageSize = parseInt(body.pageSize) // 页数
		let where = {}
		for (let i in body) {
			arr.forEach(item => {
				if (body[i] !== '' && i === item) {
					where[i] = body[i]
				}
			})
		}

		// 查询条件
		let params = {
			where: where,
			offset: (currentPage - 1) * pageSize,
			limit: pageSize
		}
		if (model.rawAttributes.sort) {
			params.order = [
				['sort', 'ASC']
			]
		}
		// 查询
		await model.findAndCountAll(params).then(result => {
			let obj = {
				currPage: parseInt(body.currentPage),
				list: result.rows,
				pageSize: parseInt(body.pageSize),
				totalCount: result.count,
				totalPage: Math.ceil(result.count / parseInt(body.pageSize))
			}
			resSuccess(res, obj)
		}).catch(err => {
			resErr(res, err)
		})
	},
	// 查询列表
	list: async (model, body, res) => {
		let params = {}
		if (model.rawAttributes.sort) {
			params.order = [
				['sort', 'ASC']
			]
		}
		await model.findAll(params).then(result => {
			resSuccess(res, result)
		}).catch(err => {
			resErr(res, err)
		})
	},
	// 查询详情
	info: async (model, body, res) => {
		let params = {
			where: { id: body.id },
			raw: true
		}
		await model.findOne(params).then(result => {
			resSuccess(res, result)
		}).catch(err => {
			resErr(res, err)
		})
	},
	// 更新
	update: async (model, body, res) => {
		body.updated_time = Date.parse(new Date()) / 1000
		delete body.password
		await model.update(body, {
			where: { id: body.id }
		}).then(result => {
			resSuccess(res, null)
		}).catch(err => {
			resErr(res, err)
		})
	},
	// 删除
	del: async (model, body, res) => {
		await model.destroy({
			where: { id: body.id }
		}).then(result => {
			resSuccess(res, null)
		}).catch(err => {
			resErr(res, err)
		})
	}
}
module.exports = obj
